package priv.tuyou.redis.limit;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 固定窗口-限流器
 *
 * 使用一个过期时间等于限流周期的key缓存来实现
 * @author tuyou_cd
 * @date 2021/4/23 13:37
 */
public class FixWindowRateLimiter extends AbstractRateLimiter {

    public FixWindowRateLimiter(JedisPool pool, int period, int limit) {
        super(pool, period, limit);
    }

    @Override
    public boolean visit(int count) {
        Jedis resource = pool.getResource();
        try {
            String s = resource.get(key);
            if (s == null) {
                String result = resource.set(key, "1", "NX", "EX", period);
                if (!"OK".equals(result)) {
                    return false;
                }
                s = "1";
            }

            if (Integer.parseInt(s) >= limit) {
                return false;
            }

            resource.incr(key);
        } finally {
            //记得回收连接，否则会一直被占用
            resource.close();
        }
        return true;
    }
}
